﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using RBS.Common;
using RBS.Common.JsonEntity;
using RBS.Core.Extension;
using RBS.Core.Model;
using RBS.Web.Hotel.Controllers;
using RBS.Web.Hotel.Models.Order;
using Webdiyer.WebControls.Mvc;

namespace RBS.Web.Hotel.Areas.Settlement.Controllers
{
    public class SmController : BaseController
    {

        #region 预订信息
       
        public ActionResult Index(int id = 1, string kword = null)
        {
            const int pageSize = 10;
            var bll = new RBS.Core.BLL.Hotel.H_Hotel_Seat();
            // var admin = GetAdminInfo(); //取得当前管理员信息
            if (kword != null) kword = kword.Replace("'", "");
            var strTemp = new StringBuilder();
            if (!string.IsNullOrEmpty(kword))
            {
                //strTemp.Append(" and (H_UID like  '%" + kword + "%' or H_UserName like '%" + kword + "%')");
            }
            string strWhere = " and HotelId =" + CurrentUser.HotelId + strTemp.ToString();
            const string orderby = " id  desc";
            var startIndex = id;

            int totalItems = 0; //要分页的总记录数
            DataTable dt = bll.GetList(pageSize, startIndex, strWhere, orderby, out totalItems).Tables[0];
            //PagedList构造函数 
            var list = IListDataSet.DataTableToIList<RBS.Core.Model.Hotel.H_Hotel_Seat>(dt);
            PagedList<RBS.Core.Model.Hotel.H_Hotel_Seat> arts = null;
            if (list != null)
                arts = new PagedList<RBS.Core.Model.Hotel.H_Hotel_Seat>(list, id, pageSize, totalItems);
            else
            {
                list = new List<RBS.Core.Model.Hotel.H_Hotel_Seat>();
                arts = new PagedList<RBS.Core.Model.Hotel.H_Hotel_Seat>(list, id, pageSize, totalItems);
            }
            return View(arts);
        } 
        [HttpPost]
        public JsonResult GetOrderList(int seatId, int hotelId)
        {
            var ret = new RBS.Common.JsonEntity.JsonReturnMessages();
            var modelList =
                new RBS.Core.BLL.D_Order().GetModelList(
                    " H_Id=" + hotelId + " and DineTable=" + seatId + " and OrderState=4");// and DATEADD(MINUTE,30, OrderTime)> GETDATE()
            ret.IsSuccess = true;
            ret.Data = modelList;
            return Json(ret);
        } 
        [HttpPost]
        public JsonResult GetOrderDetails(int orderId)
        {
            var ret = new RBS.Common.JsonEntity.JsonReturnMessages();
            var modelList =
                new RBS.Core.BLL.D_Order_Details().GetModelList(
                    " orderId=" + orderId + "");// and DATEADD(MINUTE,30, OrderTime)> GETDATE()
            ret.IsSuccess = true;
            ret.Data = modelList;
            return Json(ret);
        }
        #endregion 
        #region 结帐
        /// <summary>
        /// 结帐
        /// </summary>
        /// <param name="orderid"></param>
        /// <returns></returns>
        public ActionResult jiesuan(int orderid)
        {


            var roles = CurrentUser.RoleIds;//.Split(',');

            if (roles.Count() == 1 && roles== "5")
            {
                return Content("非法进入！");
            } 
            //是否可以编辑菜单
            ViewBag.Isedit = roles.Contains("1") || roles.Contains("2") || roles.Contains("4");
            
            var model = new OrderViewModel
            {
                OrderModel = new RBS.Core.BLL.D_Order().GetModel(orderid),
                OrderDetailsModel = new RBS.Core.BLL.V_OrderDetails().GetModelList("OrderId=" + orderid)
            };
            model.SeateName = new RBS.Core.BLL.Hotel.H_Hotel_Seat().GetModelByCache(Convert.ToInt32(model.OrderModel.DineTable)).Name;
            //总金额
            model.OrderModel.OrderAmount = model.OrderDetailsModel.Sum(c => c.Num * c.DisAmount*c.Weight);
            var count = 0;
            //酒店优惠券信息
            DataTable dt = new RBS.Core.BLL.P_Advertis_Payment().GetList(10, 1, " and HotelId=" + model.OrderModel.H_Id + "", " ValidEndTime desc ", out count).Tables[0];
            model.HotelDeed = IListDataSet.DataTableToIList<RBS.Core.Model.P_Advertis_Payment>(dt);
            //食客信息
            if (model.OrderModel.U_Id > 0)
            {
                model.User = new RBS.Core.BLL.U_User().GetModelByCache(model.OrderModel.U_Id);
                model.UserIntegration = new RBS.Core.BLL.U_User_Integration().GetIntegralCount(model.OrderModel.U_Id);
                dt = new RBS.Core.BLL.P_Advertis_Payment().GetListByUser(10, 1, "and U_Id= " + model.User.Id + " and HotelId=" + model.OrderModel.H_Id + "  and ValidEndTime>=GETDATE()", " ValidEndTime desc ", out count).Tables[0];
                IListDataSet.DataTableToIList<RBS.Core.Model.P_Advertis_Payment>(dt);
                model.UserDeed = IListDataSet.DataTableToIList<RBS.Core.Model.P_Advertis_Payment>(dt);  
                model.OrderUser = new RBS.Core.BLL.P_Order_User().GetModelList(" OrderId="+orderid);
            }
            model.Seetlement = new D_Settlement();

            
            if(model.OrderUser!=null){
                // 积分
                var pOrderUser = model.OrderUser.FirstOrDefault(c => c.DeedType == "0");
                if (pOrderUser != null)
                    model.Seetlement.JF = pOrderUser.DeedNum;

                 //送菜券   
                 pOrderUser = model.OrderUser.FirstOrDefault(c => c.DeedType == "1");
                 if (pOrderUser != null){
                    model.Seetlement.SendFood = pOrderUser.DeedNum;
                    model.Seetlement.SendFoodId = pOrderUser.DeeId;
                  } 
                //消费券  
                  pOrderUser = model.OrderUser.FirstOrDefault(c => c.DeedType == "2");
                  if (pOrderUser != null)
                  {
                      model.Seetlement.Consumption = pOrderUser.DeedNum;
                      model.Seetlement.ConsumptionId = pOrderUser.DeeId;
                  }
                //广告券
                  pOrderUser = model.OrderUser.FirstOrDefault(c => c.DeedType == "3");
                  if (pOrderUser != null)
                  {
                      model.Seetlement.Advertis = pOrderUser.DeedNum;
                      model.Seetlement.AdvertisId = pOrderUser.DeeId;
                  }
            }
                  model.Seetlement.OrderAmount =model.OrderModel.OrderAmount;
                  model.Seetlement.Amount = model.OrderModel.OrderAmount;

           
            return View(model);
        } 
         
        [HttpPost]
        public ActionResult jiesuan(OrderViewModel orderViewModel,FormCollection collection)
        {
            var ret = new RBS.Common.JsonEntity.JsonReturnMessages();
            if(orderViewModel.Seetlement.RecAmount<=0)
            {
                ret.IsSuccess = false;
                ret.Msg = "实收金额不能小于零元！";
                return Json(ret);
            }


            var orderBll = new RBS.Core.BLL.D_Order(); 
            var a = orderViewModel;
            var order = orderBll.GetModel(a.OrderModel.Id);

            //添加结帐单
            var settlement = new RBS.Core.Model.D_Settlement
            { 
                HotelId = order.H_Id,
                OrderId = order.Id,
                UserId = order.U_Id,
                OrderNo = orderViewModel.Number,
                PayType = orderViewModel.Seetlement.PayType,
                PayTime =DateTime.Now, 
                RecAmount = orderViewModel.Seetlement.RecAmount,
                GiveAmount = orderViewModel.Seetlement.GiveAmount,
                OrderAmount = orderViewModel.Seetlement.OrderAmount,
                Amount = orderViewModel.Seetlement.Amount,
                DisAmount = orderViewModel.Seetlement.DisAmount,
                PaidAmount = orderViewModel.Seetlement.PaidAmount,   
                JF = orderViewModel.Seetlement.JF,
/*
                SendFoodId = orderViewModel.Seetlement.JF,
                SendFood = orderViewModel.Seetlement.JF,
                ConsumptionId = orderViewModel.Seetlement.JF,
                Consumption =  orderViewModel.Seetlement.JF,
                AdvertisId = orderViewModel.Seetlement.JF,
                Advertis = orderViewModel.Seetlement.JF,*/  
            };
            new RBS.Core.BLL.D_Settlement().Add(settlement); 
            //修改订单  
            order.OrderAmount = a.Seetlement.OrderAmount;
            order.RecAmount = a.Seetlement.RecAmount;
            order.DisAmount = a.Seetlement.DisAmount;
            order.AccAmount = a.Seetlement.GiveAmount;
            order.PayType = a.Seetlement.PayType;
            order.PayTime = DateTime.Now; 
            if (order.U_Id == RBSKeys.Visitor)
            {
                order.OrderState = (int)RBS.Common.RBSEnums.OrderStatus.Done;
            }
            else
            {
                order.OrderState = (int)RBS.Common.RBSEnums.OrderStatus.ToComment;   
                //赠送积分
                //AddIntegration(order.H_Id, order.AccAmount, order.U_Id);
              
            } 
            order.LastModifyUser = CurrentUser.H_UserName;
            order.LastModifyDate = DateTime.Now;
            orderBll.Update(order);  
             
            //清桌  
            // new RBS.Core.BLL.Hotel.H_Hotel_Seat().UpdateStatus(a.OrderModel.H_Id, a.OrderModel.DineTable.ToString(), 0);
            //积分，优惠券赠送 
            if (collection["HotelDeedCKB"] != null && order.U_Id>0)
            {
                var hdeed = collection["HotelDeedCKB"].Split(','); 
                foreach (var s in hdeed)
                {
                    JsonData jsonData = ApiRepository.Get("api/Deed/HotelDeed?uid=" + order.U_Id + "&apid=" + s + "&num=1");
                }  
            } 
            ret.IsSuccess = true;
            ret.Msg = "订单结算成功！";
            ret.Data = Url.Action("OrderPint", "Print", new {orderid = order.Id});
            return Json(ret);
          

          /*  var orderBll = new RBS.Core.BLL.D_Order();
            var a = orderViewModel;
            var order = orderBll.GetModel(a.OrderModel.Id);

            order.OrderAmount = a.OrderModel.OrderAmount;
            order.RecAmount = a.OrderModel.RecAmount;
            order.DisAmount = a.OrderModel.DisAmount;
            order.AccAmount = a.OrderModel.AccAmount;
            order.PayType = "现金";
            order.PayTime = DateTime.Now; 
            if (order.U_Id == RBSKeys.Visitor)
            {
                order.OrderState = (int)RBS.Common.RBSEnums.OrderStatus.Done;
            }
            else
            {
                order.OrderState = (int)RBS.Common.RBSEnums.OrderStatus.ToComment;
                //积分清算
                AddIntegration(order.H_Id, order.AccAmount, order.U_Id);
            } 
            order.LastModifyUser = CurrentUser.H_UserName;
            order.LastModifyDate = DateTime.Now;
            orderBll.Update(order);
            //清桌  
            new RBS.Core.BLL.Hotel.H_Hotel_Seat().UpdateStatus(a.OrderModel.H_Id, a.OrderModel.DineTable.ToString(), 0);
            var settlement = new RBS.Core.Model.D_Settlement
            {
                HotelId = order.H_Id,
                OrderNo = a.Number,
                OrderId = order.Id,
                OrderAmount = order.OrderAmount,
                RecAmount = order.RecAmount,
                GiveAmount = order.AccAmount,
                DisAmount = order.DisAmount,
                PayType = order.PayType,
                PayTime = order.PayTime,
                JF = orderViewModel.Seetlement.JF
            };
            new RBS.Core.BLL.D_Settlement().Add(settlement);

            return Content(order.Id.ToString());*/
        }

         
        public ActionResult UpdateNum()
        {
            return View();
        }
          [HttpPost]
        public ActionResult UpdateNum(FormCollection collection)
        { 
              var  jet=new JsonReturnMessages(); 
            var oid = collection["oid"];
            var cid = collection["cid"];
            var num = collection["num"];
            var editnum1 = collection["editnum1"];
              var bll = new RBS.Core.BLL.D_Order_Details();
              var orderbll = new RBS.Core.BLL.D_Order();  
              var order=orderbll.GetModelByCache(Convert.ToInt32(oid));
              if (order.H_Id != CurrentUser.HotelId)
              {
                  jet.Msg = "非法操作，请联系管理员！";
                  jet.IsSuccess = false;
                  return Json(jet);
              }
              var list = bll.GetModelList("OrderId=" + oid + " and HCId=" + cid + "");
              if (list.Any() && list.Count() == Convert.ToInt32(num))
              {
                  var count = Convert.ToInt32(num) - Convert.ToInt32(editnum1);
                  if (count > 0)
                  {
                      var ids = "";
                      for (int i = 0; i < count; i++)
                      {
                          ids += list[i].Id + ",";
                      }
                      bll.DeleteList(ids.TrimEnd(','));
                  } 
                  //新增
                count = Convert.ToInt32(editnum1) - Convert.ToInt32(num);
                if (count>0){
                  for (int i = 0; i < count; i++)
                  {
                      bll.Add(list[0]);
                  }
               }
              } 
              jet.Msg = "成功！";
              jet.IsSuccess = true;
              return Json(jet); 
    }

        //保证金
        public void AddIntegration(int hotelId, decimal point, int userid)
        {
            var bllIntegration = new RBS.Core.BLL.U_User_Integration();
            var bllRecognizance = new RBS.Core.BLL.Hotel.H_Hotel_Recognizance();
            //添加积分
            var model = new RBS.Core.Model.U_User_Integration
            {
                UserId = userid,
                Point = (int)point,
                PointTime = DateTime.Now,
                HotelId = hotelId,
                Type = (int)RBSEnums.IntegraType.酒店赠送
            };
            //扣除保证金
            var model1 = new RBS.Core.Model.Hotel.H_Hotel_Recognizance
            {
                HotelId = hotelId,
                Money = -(point / 100),
                RType = 4,
                Time = DateTime.Now
            };
            bllIntegration.Add(model);
            bllRecognizance.Add(model1); 
        }  
        #endregion

        #region 开台

        /// <summary>
        /// 开台
        /// </summary>
        /// <returns></returns>
        public ActionResult Kt(int seatId)
        {
            var seat = new RBS.Core.BLL.Hotel.H_Hotel_Seat().GetModel(seatId);

            var order = new RBS.Core.Model.D_Order
            {
                OrderChannel = "店面",
                H_Id = seat.HotelId,
                DineTable = seatId,
                Dinecondition = seat.Category,
                ReserveDate = DateTime.Now.ToString("yyyy-MM-dd"),
                ReserveTime = DateTime.Now.ToString("HH:mm:ss"),
                OrderTime = DateTime.Now,
                ContactUser = "到店食客",
                LastModifyDate = DateTime.Now,
                PayTime = DateTime.Now,
                CreateTime = DateTime.Now,
                U_Id = RBSKeys.Visitor

            };
            order.OrderTime = Convert.ToDateTime(order.ReserveDate + " " + order.ReserveTime);
            order.HotelName = new RBS.Core.BLL.Hotel.H_Hotels().GetModelByCache(order.H_Id).H_Name;
            var bll = new RBS.Core.BLL.D_Order();
            order.OrderState = 4;
            order.Id = bll.Add(order);
            return RedirectToAction("Dc", new { hid = order.H_Id, oid = order.Id });
        }
  

       /* [HttpPost]
        public ActionResult Kt(FormCollection collection)
        {
            //修改订单
            var ordermodel = AddOrder(collection);
            //var uid = Convert.ToInt32(User.Identity.Name);
            //修改桌位信息  
            // UpdateSeatStatus(collection["DineTable"], collection["OldDineTable"], int.Parse(collection["H_Id"]));
            //修改菜单
            //UpdateDetail(oid, uid);  
            return RedirectToAction("Dc", new { hid = ordermodel.H_Id, oid = ordermodel.Id });
        }
 

        public RBS.Core.Model.D_Order AddOrder(FormCollection collection)
        {
            var oid = -1;
            var a = collection;
            var model = new RBS.Core.Model.D_Order
            {
                OrderChannel = "店面",
                ContactUser = collection["ContactUser"],
                ContactMobile = collection["ContactMobile"],
                OrderRemark = collection["OrderRemark"],
                ReserveDate = collection["ReserveDate"],
                ReserveTime = collection["ReserveTime"],
                DineNum = int.Parse(collection["DineNum"]),
                H_Id = int.Parse(collection["H_Id"]),
                DineTable = int.Parse(collection["DineTable"]),
                Dinecondition = collection["Dinecondition"],
                PayTime = DateTime.Now,
                CreateTime = DateTime.Now,
               /* U_Id = Convert.ToInt32(User.Identity.Name),#1#
                LastModifyDate = DateTime.Now
            };
            model.OrderTime = Convert.ToDateTime(model.ReserveDate + " " + model.ReserveTime);
            model.HotelName = new RBS.Core.BLL.Hotel.H_Hotels().GetModelByCache(model.H_Id).H_Name;
            var bll = new RBS.Core.BLL.D_Order();
            try
            {
                if (collection["Id"] != "0")
                {
                    model.Id = Convert.ToInt32(collection["Id"]);
                    model.OrderState = 4;
                    bll.Update(model);
                }
                else
                {
                    model.OrderState =4;
                    oid = bll.Add(model);
                    model.Id = oid;
                }
            }
            catch
            {
                oid = -1;
            }
            return model;
        }
*/


        /// <summary>
        /// 预定
        /// </summary>
        /// <returns></returns>
        public ActionResult Yd()
        {
            return View();
        }
        /// <summary>
        /// 点菜
        /// </summary>
        /// <returns></returns>
        public ActionResult Dc(int hid,int oid)
        {
            ViewBag.HID = hid;
            ViewBag.OID = oid;
            return View();
        }  
        [HttpPost]
        public ActionResult Dc(FormCollection collection)
        {
            var oid = Convert.ToInt32(collection["oid"]);
            UpdateDetail(oid,-1);
            return RedirectToAction("Index");
        }
        #endregion

        #region API
        public JsonResult GetCategory(int hid)
        {  
            JsonData jsonData = ApiRepository.Get("api/hotel/Cookbook?hid=" + hid);
            return Json(jsonData,JsonRequestBehavior.AllowGet); 
        }
         
        /// <summary>
        /// 获取菜谱
        /// </summary>
        /// <param name="hid"></param>
        /// <param name="cid"></param>
        /// <returns></returns>
        public JsonResult GetCookbook(int hid, int cid)
        {
            JsonData jsonData = cid == 0 ? ApiRepository.Get("api/hotel/Cookbook?type=Cookbook&hid=" + hid) : ApiRepository.Get("api/hotel/Cookbook?type=Cookbook&hid=" + hid + "&cid=" + cid);
             return Json(jsonData);
        }
         
        [AcceptVerbs(HttpVerbs.Post)]
        public JsonResult OrderTempDetail(FormCollection collection)
        {
            var model = new RBS.Core.Model.D_Order_Details()
            {
                HCId = Convert.ToInt32(collection["HCId"]),
                IsGuest = Convert.ToInt32(collection["IsGuest"]),
                CName = collection["CName"],
                Num = Convert.ToInt32(collection["Num"]),
                Price = Convert.ToDecimal(collection["Price"]),
                UId = Convert.ToInt32(collection["UId"]),
                DisAmount = 0,
                State = 0
            }; 
            var detailTemp = GetModelByCache(model);
            var jsonData = new JsonData
            {
                Success = true,
                Data = detailTemp
            };
            return Json(jsonData); 
        }
        public List<RBS.Core.Model.D_Order_Details> GetModelByCache(RBS.Core.Model.D_Order_Details m)
        {
            List<RBS.Core.Model.D_Order_Details> list;
            if (Session[RBSKeys.SESSION_SHOPCAR_INFO] == null)
            {
                list = new List<D_Order_Details> { m };
                Session[RBSKeys.SESSION_SHOPCAR_INFO] = list;
            }
            else
            {
                //如果购物车不为空时 刚判断 该商品的信息是否存在购物车中 如果 存在则 把该商品的数量加上1  
                list = Session[RBSKeys.SESSION_SHOPCAR_INFO] as List<RBS.Core.Model.D_Order_Details>;
                if (list != null)
                {
                    var item = list.FirstOrDefault(c => c.HCId == m.HCId && c.OrderId == m.OrderId);
                    if (item == null)
                    {
                        if (m.Num > 0)
                        {
                            list.Add(m);
                        }
                    }
                    else
                    {
                        item.Num = item.Num + m.Num;
                        if (item.Num <= 0)
                        {
                            list.Remove(item);
                        }
                    }
                    Session[RBSKeys.SESSION_SHOPCAR_INFO] = list;

                }
                else
                {
                    list.Add(m);
                    Session[RBSKeys.SESSION_SHOPCAR_INFO] = list;
                }
            }
            return (List<RBS.Core.Model.D_Order_Details>)Session[RBSKeys.SESSION_SHOPCAR_INFO];

        }


        public void UpdateDetail(int orderId, int uid)
        {
            var bll = new RBS.Core.BLL.D_Order_Details();
            if (!bll.ExistsOrderId(orderId, uid))
            {
                var detailTemp = (List<RBS.Core.Model.D_Order_Details>)Session[RBSKeys.SESSION_SHOPCAR_INFO];
                if (detailTemp != null && detailTemp.Any())
                {
                    foreach (var item in detailTemp)
                    {
                        item.OrderId = orderId;
                        item.State = 1;
                        item.UId = uid;
                        new RBS.Core.BLL.D_Order_Details().Add(item);
                    }
                }

            }
            else
            {
                var items = bll.GetModelList(" OrderId=" + orderId);
                foreach (var dOrderDetailse in items)
                {
                    bll.Delete(dOrderDetailse.Id);
                }
                var detailTemp = (List<RBS.Core.Model.D_Order_Details>)Session[RBSKeys.SESSION_SHOPCAR_INFO];
                foreach (var item in detailTemp)
                {
                    item.OrderId = orderId;
                    item.State = 1;
                    item.UId = uid;
                    new RBS.Core.BLL.D_Order_Details().Add(item);
                }
                //订单创建成功后移除购物车信息 
            }
            //订单创建成功后移除购物车信息
            Session.Remove(RBSKeys.SESSION_SHOPCAR_INFO);
        }


        public ActionResult OrderTemp(int hotelid, int orderid = 0)
        {
            //修改订单 
            var uid = RBSKeys.Visitor;
            //修改菜单
            if (orderid > 0)
            {
                UpdateDetail(orderid, uid);
                new RBS.Core.BLL.D_Order().UpdateOrderStatus(orderid, (int)RBS.Common.RBSEnums.OrderStatus.Dining);
                return RedirectToAction("Index");
            }
            else
            {
                return RedirectToAction("Index");
            }
        }
        #endregion

    }
}
